/**
 * 
 */
package info.niwota.group;

import java.io.File;
import java.text.MessageFormat;
import java.util.Date;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.text.TextUtils;

/**
 * @author qiangli
 *
 */
public class MailTemplate {

	//private static final String TAG = "MailTemplate";

	private MailTemplate() {
	}

	private static String toMailtoString(String to, String subj) {
		StringBuilder sb = new StringBuilder("mailto:");
		sb.append(to);
		sb.append("?subject=");
		sb.append(Uri.encode(subj));
		return sb.toString();
	}

	public static void send(Context ctx, EtalkMessage msg) throws Exception {
		send(ctx, msg.id, msg.to, msg.subject, msg.body, msg.audio, msg.attach);
	}

	/**
	 * 
	 * @param ctx
	 * @param id
	 * @param emails
	 * @param subject
	 * @param msg
	 * @param uri could be null
	 * @param attach could be null
	 * @throws Exception
	 */
	private static void send(Context ctx, String id, String emails, String subject, String msg,
			String audio, String attach) throws Exception {
		File file = null;
		File afile = null;
		try {
			//audio
			if (audio != null) {
				file = new File(audio);
				long len = file.length();
				if (len > Constants.FILE_SIZE_LIMIT) {
					throw new Exception("file size too big: " + len);
				}
				//default text message
				if (TextUtils.isEmpty(msg)) {
					String sender = Preferences.getSender(ctx);
					if (TextUtils.isEmpty(sender) == false) {
						msg = ctx.getString(R.string.email_message_body, sender);
					}
				}
			}
			//attached file
			if (attach != null) {
				if (attach.startsWith("http://") || attach.startsWith("https://")) {
					//http or https
					//prepend the link to the msg
					final String tpl = "<a href=\"{0}\">{0}</a><br><br>"; //TODO move to external file 
					msg = MessageFormat.format(tpl, attach) + nvl(msg);
				} else {
					afile = Files.toFile(attach);
					if (!afile.exists()) {
						afile = null;
					}
					long len = afile.length();
					if (len > Constants.FILE_SIZE_LIMIT) {
						throw new Exception("file size too big: " + len);
					}
				}
			}
		} catch (Exception e) {
			throw e;
		}
		//
		try {
			String[] tos = Utils.toStringArray(emails);
			String body = buildContent(ctx, subject, msg, tos, true);
			//
			Email.send(ctx, id, emails, subject, body, file, afile);
		} catch (Exception e) {
			throw e;
		}
	}

	private static String buildContent(Context ctx, String subj, String msg, String[] tos,
			boolean html) {
		// version, email, email, signature
		//
		String re = Preferences.getReturnEmail(ctx);
		StringBuilder sb = new StringBuilder();
		if (re == null) {
			re = "";
		} else {
			sb.append(re);
			sb.append(",");
		}
		for (String s : tos) {
			if (s.equalsIgnoreCase(re)) {
				continue;
			}
			sb.append(s);
			sb.append(",");
		}
		//
		String sig = formatSignature(ctx, html);
		msg = nvl(msg);
		if (html) {
			String u1 = toMailtoString(re, subj);
			String u2 = toMailtoString(sb.toString(), subj);
			CharSequence b = Utils.readResource(ctx, R.raw.email_body);
			String tpl = b.toString();
			return MessageFormat.format(tpl, msg, u1, u2, sig);
		} else {
			if (TextUtils.isEmpty(re)) {
				return ctx.getString(R.string.email_body_noreply, msg, sig);
			}
			String u1 = toMailtoString(re, subj);
			String u2 = toMailtoString(sb.toString(), subj);
			return ctx.getString(R.string.email_body, msg, u1, u2, sig);
		}
	}

	private static String formatSignature(Context ctx, boolean html) {
		final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(ctx);
		String sig = p.getString(Preferences.SIGNATURE, "");
		boolean loc = p.getBoolean(Preferences.SIGNATURE_LOCATION, false);
		boolean time = p.getBoolean(Preferences.SIGNATURE_TIME, false);
		String photo = p.getString(Preferences.SIGNATURE_PHOTO, null);
		//
		return formatSignature(ctx, html, sig, loc, time, photo);
	}

	public static String formatSignature(Context ctx, boolean html, String sig, boolean loc, boolean time, String photo) {
		final String br = "<br />";
		final String eol = "\n";
		//
		StringBuilder sb = new StringBuilder(sig);
		if (html) {
			sb.append(br);
			if (loc) {
				String l = LocationUtils.getLocation(ctx, "");
				sb.append(l);
				sb.append(br);
			}
			if (time) {
				String t = getTime();
				sb.append(t);
				sb.append(br);
			}
			if (!TextUtils.isEmpty(photo)) {
				if (photo.startsWith("http://") || photo.startsWith("https://")) {
					sb.append("<img src=\""+ photo + "\" alt=\"photo\" />");
				} else {
					sb.append("<img src=\"http://"+ photo + "\" alt=\"photo\" />");
				}
				sb.append(br);
			}
		} else {
			sb.append(eol);
			if (loc) {
				sb.append(LocationUtils.getLocation(ctx, ""));
				sb.append(eol);
			}
			if (time) {
				sb.append(getTime());
				sb.append(eol);
			}
			if (!TextUtils.isEmpty(photo)) {
				sb.append(photo);
				sb.append(eol);
			}
		}
		return sb.toString();
	}

	public static void startSendActivity(Context ctx, EtalkMessage msg) throws Exception {
		startSendActivity(ctx, msg.name, msg.to, msg.subject, msg.body, msg.audio, msg.attach, true);
	}
	
	public static void startSendActivity(Context ctx, String name, String emails,
			String subject, String msg, String audio, String attach) throws Exception {
		startSendActivity(ctx, name, emails, subject, msg, audio, attach, false);
	}

	private static void startSendActivity(Context ctx, String name, String emails,
			String subject, String msg, String audio, String attach, boolean noop) throws Exception {
		try {
			//for default services, we assume attach is a link only or audio is null
			String path = null;
			if (attach != null) {
				if (attach.startsWith("http")) {
					msg = attach + "\r\n" + msg;
				} else {
					path = attach;
				}
			}
			if (audio != null) {
				path = audio;
			}
			//
			Uri uri = null;
			if (path != null) {	
				File file = new File(path);
				long len = file.length();
				if (len > Constants.FILE_SIZE_LIMIT) {
					throw new Exception("file size to big: " + len);
				}
				path = file.getPath();
				uri =  Files.toUri(path);
			}
			//
			String[] tos = Utils.toStringArray(emails);
			String body = buildContent(ctx, subject, msg, tos, false);
			//Uri stream = uri;// Uri.parse(file.toURI().toString());
			//
			Intent i = new Intent();
			i.setAction(Intent.ACTION_SEND);
			i.setType("message/rfc822");
			//i.setType("*/*");
			//
			// i.setType("audio/3gpp");
			// i.setType("text/plain"); //emulator
			// i.setType("message/rfc822"); //phone
			//
			// email
			i.putExtra(Intent.EXTRA_EMAIL, tos);
			i.putExtra(Intent.EXTRA_SUBJECT, subject);
			i.putExtra(Intent.EXTRA_TEXT, body);
			
			//
			if (uri != null) {
				i.putExtra(Intent.EXTRA_STREAM, uri);
			}
			//TODO attachment?
			//
			// mms
			i.putExtra("address", emails);
			i.putExtra("exit_on_sent", true);
			i.putExtra("sms_body", body);
			//
			i.putExtra(EtalkIntent.EXTRA_NAME, name);
			i.putExtra(EtalkIntent.EXTRA_URI, path);
			i.putExtra(EtalkIntent.NOOP, noop);
			
			//
			String ti = ctx.getString(R.string.menu_composewith); 
			ctx.startActivity(Intent.createChooser(i, ti));
		} catch (Exception e) {
			e.printStackTrace();
			//
			throw e;
		}
	}
	
	private static String getTime() {
		return new Date().toGMTString();
	}

	private static String nvl(String s) {
		return (s == null ? "" : s);
	}

}
